﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Speech.Synthesis;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace workstation.utils
{
    public class SpeechSynthesizerHelper
    {
        public delegate void SpeechDelegate(string content);
        private Dictionary<string, SpeechSynthesizer> speechSynthesizers = new Dictionary<string, SpeechSynthesizer>();

        //点击开始按钮 
        public void serialMessageEventHandle( string content)
        {
            foreach (SpeechSynthesizer item in speechSynthesizers.Values)
            {
                try
                {
                    if (item != null) {
                        item.SpeakAsyncCancelAll();
                        item.Dispose();
                    }
                }
                catch (Exception ex)
                {
                }
            }

            SpeechSynthesizer speechSynthesizer = new SpeechSynthesizer();
            speechSynthesizer.Rate = -2;//阅读速度
            speechSynthesizer.Volume = 100;
            int repereatCount = 2;
            speechSynthesizer.SpeakCompleted += new EventHandler<SpeakCompletedEventArgs>((object sender, SpeakCompletedEventArgs e) =>
            {
                if (repereatCount > 0)
                {
                    if (speechSynthesizer != null) {
                        speechSynthesizer.SpeakAsync(content);
                    }
                    repereatCount--;
                }
            });
            speechSynthesizer.SpeakAsync(content);
            //if (speechSynthesizers.ContainsKey(serialPort))
            //{
             //   speechSynthesizers.Remove(serialPort);
            //}
            //speechSynthesizers.Add(serialPort, speechSynthesizer);

        }


        private static SpeechSynthesizerHelper _SingletonSecond = null;

        static SpeechSynthesizerHelper()
        {
            _SingletonSecond = new SpeechSynthesizerHelper();
        }

        public static SpeechSynthesizerHelper CreateInstance()
        {
            return _SingletonSecond;
        }
    }
}
